#!/usr/bin/env bash
# This script builds the .deb packages by changing debian/changelog
# SPDX-FileCopyrightText: © 2020 Siemens AG

# SPDX-License-Identifier: GPL-2.0-only

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
TOP="${SCRIPT_DIR}/.."

show_help() {
  cat <<EOF
Usage: fo-debuild [options]
  -s or --no-sign    : do not sign packages
  -h or --help       : this help text
  -t or --no-tar     : do not tar packages folder
EOF
}

NOSIGN=''
NOTAR=''

. "${SCRIPT_DIR}/utils.sh"

# Make sure we are in correct location
pushd $TOP

# make sure we're in a checked out git copy
if [ ! -d .git ]; then
   echo "ERROR: No Git information found. This script requires an git tree."
   exit 0
fi

# Check if GIT is available. If not, then abort.
which git >/dev/null 2>&1
if [ $? != 0 ]; then
   echo "ERROR: git command missing."
   exit 1
fi

set -o errexit -o nounset -o pipefail

## Options parsing and setup
# parse options
OPTS=$(getopt -o sht --long no-sign,help,no-tar -n 'fo-debuild' -- "$@")

if [[ $? -ne 0 ]]; then
   OPTS="--help"
fi

eval set -- "$OPTS"

while true; do
   case "$1" in
      -s|--no-sign)     NOSIGN="--no-sign" shift;;
      -h|--help)        show_help; exit;;
      -t|--no-tar)      NOTAR="1"; shift;;
      --)               shift; break;;
      *)                echo "ERROR: option $1 not recognised"; exit 1;;
   esac
done

# Get the version
VERSION=$(eval "${VERSION_COMMAND}")
VERSION="${VERSION/-rc/~rc}-1"
DISTRO=$(lsb_release --codename --short)

# Update debian/changelog
echo "Updating changelog with ${DISTRO} distro and ${VERSION} version."
debchange --distribution "${DISTRO}" \
  --newversion "${VERSION}" \
  --urgency low --maintmaint "New patch build"

utils/fo-mktar

# Clean and build packages
echo "Building packages..."
make clean
dpkg-buildpackage ${NOSIGN}

# Discard changelog changes
git checkout -- debian/changelog

# Package deb files
echo "Organizing files to ${TOP}/packages/"
find .. -type f -name "*-dbgsym*" -exec rm -rf {} \;
mkdir -p packages
mv ../*.deb packages/
mv ../fossology_${VERSION}_* packages/
mv ../fossology_${VERSION}.dsc packages/
if [[ -z "${NOTAR}" ]]; then
  echo "Packaging files as ${TOP}/fossology_${VERSION}.tar.gz"
  tar -czvf fossology_${VERSION}.tar.gz packages
  rm -rf packages
fi

popd

